﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core.DBUtility;
using Micrhard.FMCG.Server.DataAccess;
using Micrhard.FMCG.Server.DTO;
using Microhard.Core;
using Micrhard.FMCG.Server.Msg;
using Micrhard.FMCG.Server.Models;

namespace Micrhard.FMCG.Server.Impl
{
    public class CompanyImpl : ICompany
    {
        public Microhard.Core.DBUtility.ExecutedResult Add(Models.CompanyModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var op = model.ToEntity();

            try
            {
                db.Companies.AddObject(op);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, CompanyMsg.AddFailed);
                Log.Error("ICompany.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(Models.CompanyModel model)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var entity = db.Companies.SingleOrDefault(l => l.CompanyID == model.CompanyID);
            if (entity != null)
            {
                entity.Name = model.Name;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, CompanyMsg.UpdateFailed);
                Log.Error("ICompany.Update", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var entity = db.Companies.Where(l => ids.Contains(l.CompanyID));
            foreach (var e in entity)
            {
                //公司是否在使用
                var subCnt = db.Companies.Count(c => c.Com_CompanyID == e.CompanyID);
                if (e.Employees.Count == 0 &&
                    e.KAs.Count == 0 &&
                    e.Products.Count == 0 &&
                    subCnt == 0)
                {
                    db.Companies.DeleteObject(e);
                }
                else
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, string.Format(CompanyMsg.CompanyIsUsing, e.Name));
                }
            }
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, CompanyMsg.DeleteFailed);
                    Log.Error("ICompany.Delete", ex);
                }
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(Models.CompanyModel model)
        {
            throw new NotImplementedException();
        }

        public Models.CompanyModel GetModelByID(Guid id)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var model = db.Companies.SingleOrDefault(c => c.CompanyID == id).ToModel();
            if (model != null)
            {
                var mcmp = db.Companies.SingleOrDefault(c => c.CompanyID == model.Com_CompanyID);
                if (mcmp != null)
                {
                    model.MontherCompanyName = mcmp.Name;
                }
            }
            return model;
        }

        public Models.CompanyModel GetModelByModel(Models.CompanyModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.CompanyModel> Query(Models.CompanyModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            IEnumerable<Company> entities = from b in db.Companies
                                            where b.Com_CompanyID == Model.Com_CompanyID
                                            && b.CompanyType == (int)CompanyType.Sub
                                            select b;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.Name).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<CompanyModel>();
        }

        public List<Models.CompanyModel> Query(Models.CompanyModel Model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }

        public bool IsDuplicate(CompanyModel model)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var cnt = db.Companies.Count(n => n.Name == model.Name);
            return cnt > 0 ? true : false;
        }

        public List<CompanyModel> GetHQCompany()
        {
            List<CompanyModel> result = new List<CompanyModel>();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var cmp = from c in db.Companies
                      where c.CompanyType == (int)CompanyType.Heaer
                      select c;
            if (cmp.Count() > 0)
            {
                cmp.ToList().ForEach(i =>
               {
                   result.Add(i.ToModel());
               });
            }
            return result;
        }
    }
}
